// shoppingCart.js
const regeneratorRuntime = require('../../lib/runtime');
const wx = require('../../lib/wx');
const Api = require('../../utils/api.js');
const wxapp = require('../../lib/wxapp');
const Util = require('../../utils/util.js');

// 获取应用实例
const app = getApp();
Page({
  data: {
    isEmpty: false,
    carNum:0,
    btnDis: true,
    selectAll: false,
    total: 0.00,
    orderInfo: [
      {
        brand: '',
        logo: '',
        express: '',
        expressIcon: '',
        selected: false,
        list: [
          {
            color: '',
            size: '',
            productNum: 0,
            price: '',
            orignPrice: '',
            img: '',
            productInfo: '',
            selected: false,
            isOff: false,
            stock: 0,
            addDis: false,
            cutDis: true,
          }
        ],
      },
    ],
  },

  goToMenu: wxapp.handler(function* goToMenu(next, e){
    const url = e.currentTarget.dataset.url;
    wx.reLaunch({
      url,
    });

    yield next;
  }),

  delCar: wxapp.handler(function* delCar(next,e) {
      var id = e.currentTarget.dataset.id;

      var delShopCar = Api.delShopCar();
      var that = this;
    wx.showModal({
      title: '提示',
      content: '确认删除',
      success: function (res) {
        if (res.confirm) {
          console.log(111);
          wx.request({
            url: delShopCar,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'POST',
            data: {
              id: id
            },
            complete: function (res) {
              if (res.data.status == 1) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                });

                that.getCart();

              } else {
                wx.showToast({
                  title: res.data.msg,
                  image: '../../images/error.png',
                  duration: 2000,
                });
              }
            }
          });
        }

      }, complete:function(res){
        if (res.confirm) {
          console.log(111);
          wx.request({
            url: delShopCar,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            method: 'POST',
            data: {
              id: id
            },
            complete: function (res) {
              if (res.data.status == 1) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                });

                that.getCart();

              } else {
                wx.showToast({
                  title: res.data.msg,
                  image: '../../images/error.png',
                  duration: 2000,
                });
              }
            }
          });
        } 
      }

    });


      

      yield next;
  }),

  backToHome: wxapp.handler(function* backToHome(next) {
    wx.reLaunch({
      url: '../index/index',
    });

    yield next;
  }),

  selectBrand: wxapp.handler(function* selectBrand(next, e){
    const brandSelect = e.currentTarget.dataset.val;
    const pageData = this.data;
    const currentIndex = e.currentTarget.dataset.index;
    let btnDis;
    let orderInfo = pageData.orderInfo;
    if(orderInfo[currentIndex].selected){
      orderInfo[currentIndex].selected = false;
      btnDis = true;
      for(var i=0;i<orderInfo.length;i++){
        if (orderInfo[i].selected == true){
          btnDis = false;
        }
      }
    } else{
      orderInfo[currentIndex].selected = true;
      btnDis = false;
    }
    const listLength = orderInfo[currentIndex].list.length;
    var total = 0
    for(let i = 0; i < listLength; i++){
      orderInfo[currentIndex].list[i].selected  = orderInfo[currentIndex].selected;
    };

    var selectAll = true;
    for (var i = 0; i < orderInfo.length;i++){
      for(var j=0;j<orderInfo[i].list.length;j++){
        if (!orderInfo[i].list[j]['selected']){
          selectAll = false;
        }else{
          total += (orderInfo[i].list[j]['price'] * 1) * (orderInfo[i].list[j]['productNum'] * 1);
        }
      }
    }

    this.setData({
      orderInfo,
      btnDis,
      total:total,
      selectAll: selectAll
    })

    yield next;
  }),

  selectItem: wxapp.handler(function* selectItem(next, e){
    const pageData = this.data;
    const currentIndex = e.currentTarget.dataset.index;
    const brandIndex = e.currentTarget.dataset.brandIndex;
    let orderInfo = pageData.orderInfo;
    let btnDis;
    var a = true;
    var total = this.data.total;
    // console.log(orderInfo[brandIndex].list[currentIndex].price);
    if(orderInfo[brandIndex].list[currentIndex].selected){
      orderInfo[brandIndex].list[currentIndex].selected = false;
      btnDis = true;
      for (var i = 0; i < orderInfo.length; i++) {
        if (orderInfo[i].selected == true) {
          btnDis = false;
        }
      }
      
      for (var i = 0; i < orderInfo[brandIndex].list.length; i++) {
        if (orderInfo[brandIndex].list[i].selected == true) {
          a = false;
        }
      }
      if(a){
        orderInfo[brandIndex].selected = false;
      }
      total = this.data.total * 1 - orderInfo[brandIndex].list[currentIndex].price * 1*orderInfo[brandIndex].list[currentIndex].productNum*1;
    } else{
      orderInfo[brandIndex].list[currentIndex].selected = true;
      total = this.data.total * 1 + orderInfo[brandIndex].list[currentIndex].price * 1*orderInfo[brandIndex].list[currentIndex].productNum*1;
      btnDis = false;
    }
    
    var selectAll = true;
    for (var i = 0; i < orderInfo.length; i++) {
      for (var j = 0; j < orderInfo[i].list.length; j++) {
        if (!orderInfo[i].list[j]['selected']) {
          selectAll = false;
        }
      }
    }

    if (btnDis == false && a == false) {
      total = 0;
    }

    this.setData({
      orderInfo,
      btnDis,
      total: total, 
      selectAll: selectAll
    })

    yield next;
  }),

  selectAllItems: wxapp.handler(function* selectAllItems(next, e){
    const pageData = this.data;
    let selectAll = pageData.selectAll;
    let btnDis;
    if(selectAll){
      selectAll = false;
      btnDis = true;
    } else{
      selectAll = true;
      btnDis = false;
    }
    this.setData({
      selectAll,
      btnDis,
    });

    var orderInfo = this.data.orderInfo;
    var total = 0;
    for(var i=0;i<orderInfo.length;i++){
      if (selectAll) {
        orderInfo[i]['selected'] = true;
      }else{
        orderInfo[i]['selected'] = false;
      }
      for(var j=0;j<orderInfo[i].list.length;j++){
        if (selectAll) {
          orderInfo[i].list[j]['selected'] = true;
          total += orderInfo[i].list[j]['price'] * orderInfo[i].list[j]['productNum'] * 1;
        }else{
          orderInfo[i].list[j]['selected'] = false;
          total = 0;
        }
        
      }
    }
// console.log(orderInfo);
    this.setData({
      orderInfo: orderInfo,
      total: total
    });

    yield next;
  }),

  inputQty: wxapp.handler(function* inputQty(next, e) {
    let productNum = parseInt(e.detail.value) * 1;
    const currentIndex = e.currentTarget.dataset.index;
    const brandIndex = e.currentTarget.dataset.brandIndex;
    const pageData = this.data;
    let orderInfo = pageData.orderInfo;
    const stock = orderInfo[brandIndex].list[currentIndex].stock;
    if(productNum > 1) {
      orderInfo[brandIndex].list[currentIndex].cutDis = false;
    } else {
      orderInfo[brandIndex].list[currentIndex].cutDis = true;
    }

    var changeNum = 0;
    if(stock > 0 && productNum > stock){
      orderInfo[brandIndex].list[currentIndex].addDis = true;
      changeNum = stock - orderInfo[brandIndex].list[currentIndex].productNum;
      orderInfo[brandIndex].list[currentIndex].productNum = stock;
    }else{
      changeNum = productNum - orderInfo[brandIndex].list[currentIndex].productNum;
      orderInfo[brandIndex].list[currentIndex].productNum = productNum;
    }

    var total = this.data.total;console.log(changeNum);
    total = total + changeNum * orderInfo[brandIndex].list[currentIndex].price * 1;

    this.setData({
      orderInfo,
      total:total
    });

    yield next;
  }),

  cutNum: wxapp.handler(function* cutNum(next, e) {
    const pageData = this.data;
    const currentIndex = e.currentTarget.dataset.index;
    const brandIndex = e.currentTarget.dataset.brandIndex;
    let orderInfo = pageData.orderInfo;
    const stock = orderInfo[brandIndex].list[currentIndex].stock;
    let productNum = orderInfo[brandIndex].list[currentIndex].productNum*1;
    let cutDis = orderInfo[brandIndex].list[currentIndex].cutDis;
    if (cutDis) {
      return;
    }

    productNum -= 1;
    if(productNum === 1) {
      cutDis = true;
    }
    if(productNum <= 0){
      productNum=1;
      return ;
    }

    orderInfo[brandIndex].list[currentIndex].productNum = productNum;
    var total = this.data.total;
    if(orderInfo[brandIndex].list[currentIndex].selected){
        total = total-orderInfo[brandIndex].list[currentIndex].price*1;
    }

    let addDis = false;
    if(stock > 0 && productNum === stock){
      addDis = true;
    }

    this.setData({
      orderInfo,
      total:total
    });

    yield next;
  }),

  addNum: wxapp.handler(function* cutNum(next, e) {
    const pageData = this.data;
    const currentIndex = e.currentTarget.dataset.index;
    const brandIndex = e.currentTarget.dataset.brandIndex;
    let orderInfo = pageData.orderInfo;
    const stock = orderInfo[brandIndex].list[currentIndex].stock;
    let productNum = orderInfo[brandIndex].list[currentIndex].productNum*1;
    orderInfo[brandIndex].list[currentIndex].cutDis = true;
    orderInfo[brandIndex].list[currentIndex].addDis = false;
    if(stock > 0 && productNum === stock){
      return;
    }
    productNum += 1;
    if(stock > 0 && productNum === stock){
      orderInfo[brandIndex].list[currentIndex].addDis = true;
    }
    if(productNum > 1) {
      orderInfo[brandIndex].list[currentIndex].cutDis = false;
    }

    orderInfo[brandIndex].list[currentIndex].productNum = productNum;
    var total = this.data.total;
    if(orderInfo[brandIndex].list[currentIndex].selected){
      total = total+orderInfo[brandIndex].list[currentIndex].price*1;
    }

    this.setData({
      orderInfo,
      total:total
    });

    yield next;
  }),

  settlement:wxapp.handler(function* settlement(next,e) {
    var data = this.data.orderInfo;
    if (data.length < 1){
      wx.showToast({
        title: '请选择要结算的商品',
        icon: '',
        duration: 2000
      })  
      return ;
    }
    var goods = [];
    for(var i=0;i<data.length;i++){
      for(var j=0;j<data[i].list.length;j++){
        if(data[i].list[j].selected){
          goods.push(data[i].list[j]);
        }
      }
    }

    //wx.showToast({
    //  title: '正在生成订单',
    //  icon: 'loading',
    //  duration: 2000,
    //});
    const url = `../orderConfirm/orderConfirm?buyType=1&goodsInfo=${JSON.stringify(goods)}`;
    wx.navigateTo({
      url,
    });

    yield next;
  }),

  onShow: wxapp.handler(function* onShow(next) {

    yield next;
  }),

  onLoad: wxapp.handler(function* onLoad(next) {
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if(!token){
      wx.reLaunch({
        url,
      });
      return;
    }

    this.getCart();

    yield next;
  }),
  onPullDownRefresh: wxapp.handler(function* onPullDownRefresh(next) {
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    const url = '../login/login';
    if (!token) {
      wx.reLaunch({
        url,
      });
      return;
    }

    //获取购物车缓存
    var carKey = Util.carKey();
    var carData = wx.getStorageSync(carKey);


    var that = this;
    var getGoodsCar = Api.getGoodsCar();
    let postData = JSON.stringify(carData);
    // 购物车
    wx.request({
      url: getGoodsCar,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      data: {//发送给后台的数据
        token: token
      },
      complete: function (res) {
        that.setData({
          orderInfo: res.data.data
        });
      }
    });

    var getCarNum = Api.getCarNum();
    // const authTokenKey = Util.authTokenKey();
    // const token = wx.getStorageSync(authTokenKey);
    wx.request({
      url: getCarNum,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {//发送给后台的数据
        token: token
      },
      complete: function (res) {
        that.setData({ carNum: res.data.data });
      }
    });
    wx.stopPullDownRefresh();  
    yield next;
  }),
  getCart:function (){
    const authTokenKey = Util.authTokenKey();
    const token = wx.getStorageSync(authTokenKey);
    //获取购物车缓存
    var carKey = Util.carKey();
    var carData = wx.getStorageSync(carKey);


    var that = this;
    var getGoodsCar = Api.getGoodsCar();
    let postData = JSON.stringify(carData);
    // 购物车
    wx.request({
      url: getGoodsCar,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      data: {//发送给后台的数据
        token: token
      },
      complete: function (res) {
        that.setData({
          orderInfo:res.data.data
        });
      }
    });

    var getCarNum = Api.getCarNum();
    // const authTokenKey = Util.authTokenKey();
    // const token = wx.getStorageSync(authTokenKey);
    wx.request({
      url: getCarNum,
      header: {
        'content-type': 'application/json'
      },
      method: 'GET',
      data: {//发送给后台的数据
        token: token
      },
      complete: function (res) {
        that.setData({ carNum: res.data.data });
      }
    });
  }

});
